import {useAtomValue, useSetAtom} from 'jotai'
import {atomWithStorage} from 'jotai/utils'
import {useAPI} from './useAPI.ts'
import {APIError} from '../api'
import {Message} from '@arco-design/web-react'
import {useQueryClient} from 'react-query'
import {useResetWorkspaceTabs} from '../components/WorkspaceTabs'

export const JWTAtom = atomWithStorage<string | null>('jwt', null, undefined, {
  getOnInit: true,
})

export interface LoginParams {
  username: string
  password: string
}

export enum LoginType {
  ACCOUNT = 'account',
  PHONE = 'phone',
}

export const useLogin = ({username, password}: LoginParams) => {
  const api = useAPI()
  const setJWT = useSetAtom(JWTAtom)
  // const {username, password} = options
  return api.login({username, password}).then(res => {
      Message.success('登录成功')
      setJWT(res.data.data)
    }).catch(error => {
      if (error instanceof APIError) {
        Message.error(error.message)
      } else {
        Message.error('操作失败，请稍后重试')
      }
  })
}

export const useIsLogged = () => {
  const jwt = useAtomValue(JWTAtom)
  return !!jwt
}

export const useLogout = () => {
  const setJWT = useSetAtom(JWTAtom)
  const queryClient = useQueryClient()
  const resetWorkspaceTabs = useResetWorkspaceTabs()
  return () => {
    setJWT(null)
    resetWorkspaceTabs()
    queryClient.clear()
  }
}
